// 在 Cloud code 里初始化 Express 框架
var express = require('express');
var app = express();

app.set('views','cloud/views');   // 设置模板目录
app.set('view engine', 'ejs');    // 设置 template 引擎
app.use(express.bodyParser());    // 读取请求 body 的中间件

// Routers
app.get('/hello', function(req, res) {
  res.render('hello', { message: 'Congrats, you just set up your app!' });
});

var UserInstallation = AV.Object.extend("UserInstallation");

function pushAuth(installationId) {
    var body = {
        "where": {"installationId": installationId},
        "data": {"android":{"action":"net.funwoo.pandago.action.NOTICE","timestamp":Date.now(),"detail": "加油吧！少年！","event":"恭喜你已认证为触手可及的镖师","extra":"authorized"}}
    };
    pushToDevice(body);
}

function pushToDevice(body) {
    AV.Cloud.httpRequest({
        method: 'POST',
        url: 'https://leancloud.cn/1.1/push',
        headers: {
            'X-AVOSCloud-Application-Id': '9sqgh9idnbzoy27shall574wyt0g2d2ur8dyjgv8aarwrqm5',
            'X-AVOSCloud-Application-Key': '7f86a4403tutcmguwh4pz7mvdho7qf8zgf47r3eow9xv8asq',
            'Content-Type': 'application/json'
        },
        body: body
    });
}

function pushUpdate() {

}

// getUserId start
function doAuth(phone, res) {
    var params = 'account='+phone;
    AV.Cloud.httpRequest({
        method: 'POST',
        url: 'http://121.40.97.89:8181/users/login/avatar/',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: params,
        success: function(result) {
           var json = JSON.parse(result.text);
           var status = json.status;
           if (status == 403) {
                res.redirect('/failure');
           } else if (status == 200) {
           var id = json.data.user_id;
           var query = new AV.Query(UserInstallation);
           query.equalTo("userId", id);
           query.find({
               success: function(results) {
                   if (results.length === 0) {
                       res.redirect('/failure');
                       return;
                   }
                   var user = results[0];
                   user.set("isAuthorized", true);
                   user.save();
                   pushAuth(user.get("installationId"));

                   res.redirect('/success');
               },
               error: function(error) {
                   res.redirect('/failure');
               }
           });
           }
        },
        error: function(error) {
            res.redirect('/failure');
        }
    });
}

app.get('/authorize', function(req, res) {
    res.render('authorize.ejs');
});

app.get('/success', function(req, res) {
    res.render('success.ejs');
});

app.get('/failure', function(req, res) {
    res.render('failure.ejs');
});

app.get('/getUserId', function(req, res) {
    res.render('authorize.ejs');
});

app.get('/pushNotice', function(req, res) {
    res.render('pushNotice.ejs');
});

app.post('/doAuth', function(req, res) {
    var phone = req.body.phone;
    if (phone && phone.trim() !== '') {
        doAuth(phone, res);
    } else {
        res.redirect('/authorize');
    }
});

app.post('/notifyUpdate', function(req, res) {
    // if (req.body) {
    //     var appInfo = req.body;
    //     res.write(appInfo);
    //     res.end();
    // } else {
        console.log(req.body);
        res.write('{"msg":"pk"}');
        res.end();
    // }
});

app.post('/pushNotice', function(req, res) {
    var title = req.body.title;
    var detail = req.body.detail;
    var picUrl = req.body.pic;

    var body;
    if (picUrl) {
        body = {
            "data": {"android":{"action":"net.funwoo.pandago.action.NOTICE","timestamp":Date.now(),"detail": detail,"event":title,"picUrl":picUrl}}
        };
    } else {
        body = {
            "data": {"android":{"action":"net.funwoo.pandago.action.NOTICE","timestamp":Date.now(),"detail": detail,"event":title}}
        };
    }

    pushToDevice(body);
    res.redirect('/pushNotice');
});


// 最后，必须有这行代码来使 express 响应 HTTP 请求
app.listen();
